<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :on-preview="preview"
      :on-change="change"
      :on-remove="remove"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-upload2" />
    </el-upload>
    <el-progress v-if="isShowPercent" :text-inside="true" :stroke-width="26" :percentage="load" />
    <el-dialog :visible.sync="dialogVisible" title="预览">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// 创建实例
const cos = new COS({
  SecretId: 'AKIDUmoZ4IGxNWP1MQDk00jBLFsDJBnEZjeL',
  SecretKey: 'TgdSAmCNJzPaVAZjdHekZ7PRvIZv85nE'
})
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      isShowPercent: false,
      load: 0
    }
  },
  methods: {
    // 预览
    preview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 改变
    change(file, fileList) {
      this.fileList = fileList
    },
    // 删除
    remove(file) {
      const num = this.fileList.findIndex(item => item.uid === file.uid)
      this.fileList.splice(num, 1)
    },
    // 校验
    beforeUpload(file) {
      if (file.size >= 2048000) return this.$message.error('文件不能超过2MB')
    },
    // 自定义上传
    upload(params) {
      this.isShowPercent = true
      // 腾讯云上传方法
      cos.putObject({
        // 储存桶名
        Bucket: 'lalala-1308572353',
        // 区域标志
        Region: 'ap-nanjing',
        // 文件名
        Key: params.file.name,
        // 固定写法, 标准储存的意思
        StorageClass: 'STANDARD',
        // 文件对象本身
        Body: params.file,
        onProgress: (progressData) => {
          this.load = Math.round(progressData.percent * 100)
        }
      }, (err, data) => {
        console.log(err || data)
        this.fileList[this.fileList.length - 1].url = 'https://' + data.Location
        this.fileList[this.fileList.length - 1].status = 'success'
        setTimeout(() => {
          this.isShowPercent = false
          this.load = 0
        }, 500)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dis{
    ::v-deep .el-upload--picture-card{
        display: none;
    }
}
img {
  object-fit: cover
}
</style>
